/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package modules.legislation.law;

import datatypes.Antenna;
import modules.legislation.PathlossInterface;
import modules.legislation.datatypes.AntennaAndDistance;
import tools.Log;
import tools.math.MathTools;
import tools.settings.SettingsMissingException;

/**
 *
 * @author Pieter Backaert
 */
public class CustomLaw implements LawInterface {

    private double limit;
    private double[] limitsForEachAntenna;
    private static PathlossInterface instanceOfPathlossInterface;
    private double SAR_value;


    public CustomLaw(PathlossInterface instanceOfPathlossInterface , double limit){
        this.limit = limit;
        this.instanceOfPathlossInterface = instanceOfPathlossInterface;
    }

    public void initLimitsForEachAntenna(AntennaAndDistance[] ant){
        limitsForEachAntenna = new double[ant.length];

        for(int i=0 ; i<ant.length ; i++){
            AntennaAndDistance aad = ant[i];
            Antenna a = aad.getAntenna();
            limitsForEachAntenna[i] = limit;
        }
    }

    public boolean checkLegislation(AntennaAndDistance[] ant) throws SettingsMissingException {
        //initLimitsForEachAntenna(ant);

        double totalPercentage=0;
        for(int x=0; x<ant.length ; x++){

            AntennaAndDistance aad = ant[x];

            Antenna a = aad.getAntenna();
            double distance = aad.getDistance();

            //geeft een E-veldwaarde terug = [V/m]
            double result = calculate_E_field_strength(a , distance);

            if(result==0 || limit==0)
                totalPercentage += 0;
            else
                totalPercentage += Math.pow((result/limit),1);
        }

        setSAR_value(totalPercentage);
        //Log.add(this,"Result for Legislation-check : totalPercentage=" + totalPercentage);
        if( totalPercentage <= 1 )
            return true;
        else
            return false;
    }


    public double giveELimit(Antenna a){
        return giveELimit();
    }

    public double calculate_E_field_strength(Antenna a , double i) {
        double E = 0;
        try {
            double pl = instanceOfPathlossInterface.getDbPathLoss(a, i);
            double EIRP = a.getPower() + a.getGain();

            E = MathTools.calculate_simple_E_from_PathLoss(EIRP, pl, a.getFrequency() );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return E;
    }

    public double giveELimit(){
        return limit;
    }

    public double getSAR_value() {
        return SAR_value;
    }

    public void setSAR_value(double SAR_value) {
        this.SAR_value = SAR_value;
    }

}
